<?php
/**
 * Created by PhpStorm.
 * User: lizx
 * Date: 2018/1/29
 * Time: 17:28
 */

namespace app\api\controller\v1;

use app\api\controller\Errorcode;
use think\Controller;

class Base extends Controller
{
    protected $arr;

    /**
     * Api constructor.
     * @param $array
     */
    public function __construct($array){

        parent::__construct();

        $this->arr = $array;
        //验证参数
        if($validate = static::$validate[$array['command']] ?? []){
            //基础参数
            foreach ($validate['base'] as $key => $value){
                if(($array[$key] ?? '')){
                    if(!trim($array[$key])){
                        $this->outPut(999993, $key . '不合法');
                    }
                    $this->arr[$value] = $array[$key];
                }else{
                    $this->outPut(999993, $key . '不存在');
                }
            }
            if($validate['status'] ?? []){
                //根据状态判断参数
                foreach ($validate['status'] as $item){
                    //匹配规则
                    foreach ($item['key'] as $key){
                        if(!(isset($array[$key]))){
                            continue 2;
                        }
                    }
                    foreach ($item['value'] as $value){
                        //匹配状态
                        foreach ($value['rule'] as $rkey=>$rvalue){
                            if($array[$rkey] != $rvalue){
                                continue 2;
                            }
                        }
                        //验证参数
                        foreach ($value['valid'] as $vkey=>$vvalue){
                            if(!($array[$vkey] ?? '')){
                                $this->outPut(999993, $vkey . '不存在');
                            }else{
                                if(!trim($array[$vkey])){
                                    $this->outPut(999993, $vkey . '不合法');
                                }
                                $this->arr[$vvalue] = $array[$vkey];
                            }
                        }
                        break;
                    }
                }
            }
        }

    }

    /**
     * 输出
     * @param $code
     * @param string $str
     */
    public function outPut($code,$str = '')
    {
        $arr = Errorcode::$code;
        if(isset($arr[$code])){
            if(empty($str)){
                $str = $arr[$code];
            }
            echo json_encode([
                'code' => $code,
                'msg' => $str,
                'data' => []
            ]);die;
        }
    }
}